#!/usr/bin/env node

const {URLSearchParams} = require('url');

const http = require('http'),
      fs = require('fs'),
      log = console.log;

let items = load();

http.createServer((req, res) => {
    log(`${req.method} ${req.url} HTTP/${req.httpVersion}`);
    log(items);
    switch(req.method) {
        case 'GET':
          select(req,res);
          break
        case 'PUT':
          res.end('put')
          break;
        case 'POST':
          insert(req,res)
          break;
        case 'DELETE':
          res.end('delete');
          break;
        default:
          res.end('request method not support');
  }
}).listen(8080);

process.on('beforeExit',()=>save());
process.on('SIGINT',()=>{
  console.log('bye')
  save();
  process.exit(1);
});

function select(req,res){
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.end(JSON.stringify(items));
}

function insert(req,res){
  let item = '';
  req.on('data',chunk=>item+=chunk);
  req.on('end',()=>{
    item = new URLSearchParams(item);
    item = item.get('item');
    if(item!==''||typeof item !== 'undefined'){
      items.push(item);
      res.setHeader('Access-Control-Allow-Origin', '*');
      res.end('insert ok!');
    } else {
      res.setHeader('Access-Control-Allow-Origin', '*');
      res.end('items empty');
    }
  });
}

function load(){
  return JSON.parse(fs.readFileSync('./data.txt','utf8'));
}

function save(){
  fs.writeFileSync('./data/txt',JSON.stringify(items),'utf8');
}


